package com.china_goldcard.mygridview;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RelativeLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * grid视图
 */
public class MyGridView extends RelativeLayout{

    public interface OnGridItemClickListener{
          void onItemClicked(MyGridViewModel model,int index);
    }

    private OnGridItemClickListener itemClickListener;

    private Context context;

    private GridView gridView;

    private MyGridViewAdapter myGridViewAdapter;

    private List<MyGridViewModel> dataList = new ArrayList<>();

    public MyGridView(Context context){
        this(context,null);
    }

    public MyGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        getConfig(context,attrs);
        initView(context);
    }

    /**
     * 从xml中获取配置信息
     */
    private void getConfig(Context context, AttributeSet attrs) {
        //TypedArray是一个数组容器用于存放属性值
        TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.MyGridView);
        //用完务必回收容器
        attributes.recycle();
    }

    /**
     * 初始化视图
     * @param context
     */
    private void initView(Context context){
        LayoutInflater.from(context).inflate(R.layout.my_grid_view,this,true);
        gridView = (GridView) findViewById(R.id.my_gridview);
        myGridViewAdapter = new MyGridViewAdapter(context,dataList,R.layout.my_grid_view);
        gridView.setAdapter(myGridViewAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for(MyGridViewModel model : dataList){
                    model.setSelected(false);
                }
                dataList.get(position).setSelected(true);
                myGridViewAdapter.reloadData(dataList);
                if (itemClickListener!= null){
                    itemClickListener.onItemClicked(dataList.get(position),position);
                }
            }
        });
    }

    public void setItemClickListener(OnGridItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    /**
     * 加载数据
     * @param dataList
     */
    public void loadData(List<MyGridViewModel> dataList){
        this.dataList = dataList;
        myGridViewAdapter.reloadData(this.dataList);
    }

    /**
     * 取消所有的选择
     */
    public void deSelect(){
        for(MyGridViewModel model : dataList){
            model.setSelected(false);
        }
        myGridViewAdapter.reloadData(this.dataList);
    }
}
